import React, { useState, useEffect } from 'react';
import { Card, Form, Row, Col, Input, Select, Button, Table, Popconfirm, message, Badge, Divider, DatePicker } from 'antd';
import BreadcrumbBox from '@/components/Base/BreadcrumbBox';
import { withRouter } from 'react-router-dom';
import { formatBalance } from '@/utils/utils';
import { useDebounceFn, useSyncCallback, deepclone } from '@/utils';
import { Storage } from '@/assets/js/storage';
import { TOKEN } from '@/utils/constant'
import moment from 'moment';
import './index.scss';
import { 
  rechargeList,
  rechargeSum,
  callback,
} from '@/api/merchant'

let first = false
let orCToken = {}
const Deposit = (props) => {
  const [searchForm] = Form.useForm();
  const { RangePicker } = DatePicker;
  // 筛选数据
  const [values] = useState({
    "time": [moment(),moment()],
    "platformOrderId": "",
    "orderSource": "",
    "callbackStatus": "",
    "status": "",
    "merchantCode": "",
    "merchantName": "",
    "merchantNo": "",
    "walletAddress": "",
  })
  // 订单来源
  const orderSourceList = [
    { value: '1', label: 'API' },
    { value: '2', label: '后台' },
  ]
  // 回调状态
  const callbackStatusList = [
    { value: '1', label: '成功' },
    { value: '2', label: '失败' },
  ]
  // 订单状态
  const orderStatusList = [
    { value: '0', label: '未支付' },
    { value: '1', label: '已支付' },
    { value: '2', label: '已受理' },
    { value: '3', label: '已审核' },
    { value: '4', label: '成功' },
    { value: '5', label: '失败' },
  ]
  const getName = (key) =>{
    orderStatusList.forEach(item=>{
      if(parseInt(item.value)===key){
        return item.label;
      }
    })
  }
  // 分页
  const [allSum, setAllSum] = useState(0)
  const [pageSum, setPageSum] = useState(0)
  const [total, setTotal] = useState(0)
  const [currentPage, setCurrentPage] = useState(1)
  const [pageSize, setPageSize] = useState(20)
  const [dataSource, setDataSource] = useState([]);
  // 面包屑
  const breadcrumbList = ['商户订单', '充值订单']
  // 布局
  const layout1 = { sm: 24, md: 12, lg: 12, xl: 6, xxl: 6 };
  const labelCol = { sm: 24, md: 8, lg: 8, xl: 8 };
  const wrapperCol = { sm: 24, md: 16, lg: 16, xl: 16 };
  const layoutbtn = { sm: 24, md: 24, lg: 24, xl: 24, xxl: 24 };
  
  const [formData, setFormData] = useState(values)
  let [loading, setLoading] = useState(false)
  // 表单头部
  const columns = [
    {
      title: '平台订单',
      dataIndex: 'platformOrderId',
      key: 'platformOrderId',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '商户订单号',
      dataIndex: 'merchantOrderId',
      key: 'merchantOrderId',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '商户账号',
      dataIndex: 'merchantName',
      key: 'merchantName',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '商户编号',
      dataIndex: 'merchantCode',
      key: 'merchantCode',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '来源',
      dataIndex: 'source',
      key: 'source',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '创建时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '支付时间',
      dataIndex: 'payTime',
      key: 'payTime',
      align: 'center',
      render: (text: any) => text || '--',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      render: (text: string, record: any) => {
        switch (text) {
          case '0':
            return <Badge status="default" text="待审核" />;
            break;
          case '1':
          case '2':
          case '3':
            return <Badge status="warning" text="交易中" />;
            break;
          case '4':
            return <Badge status="success" text="成功" />;
            break;
          case '5':
            return <Badge status="success" text="失败" />;
            break;
          default:
            return <Badge status="error" text="未到账" />;
            break;
        }
      },
    },
    {
      title: '回调状态',
      dataIndex: 'callbackStatus',
      key: 'callbackStatus',
      align: 'center',
      render: (text: string, record: any) => {
        switch (text) {
          case 1:
            return <Badge status="success" text="成功" />;
            break;
          case 2:
            return <Badge status="error" text="失败" />;
            break;
          default:
            break;
        }
      },
    },
    {
      title: '手续费',
      key: 'fee',
      dataIndex: 'fee',
      align: 'center',
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 120,
      fixed: 'right',
      render: (text: string, record: any) => {
        return <>
          {
            record.status === 0
            ?
            <a onClick={() => {callbackFn(record.id)}}>
              手动回调
            </a>
            :
            ''
          }
        </>
      },
    }
  ];
  
  // 提交弹框表单做防抖处理
  const onFinish = async () => {
    let values = deepclone(formData)
    setPageSum(0)
    try {
      let params = {
      startDate: moment(values.time[0]).format('YYYY-MM-DD'),
      endDate: moment(values.time[1]).format('YYYY-MM-DD'),
      currentPage,
      pageSize,
        ...values,
      }
      delete params.time
      setLoading(true)
      let res =  await rechargeList(params, orCToken)
      if(res.code === 0) {
        if(res.data.records){
          let sum = 0;
          res.data.records.forEach(item=>{
            sum += item.amount;
          })
          setPageSum(sum)
        }
        setDataSource(res.data.records || [])
        setTotal(res.data.total)
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  };
  const getTotal = async () => {
    let values = deepclone(formData)
    try {
      let params = {
      startDate: moment(values.time[0]).format('YYYY-MM-DD'),
      endDate: moment(values.time[1]).format('YYYY-MM-DD'),
      currentPage,
      pageSize,
        ...values,
      }
      delete params.time
      let res =  await rechargeSum(params, orCToken)
      if(res.code === 0) {
        setAllSum(res.data)
      }
    } catch (error) {
      console.log(error)
    }
  };
  const exportExcel = async () => {
    let values = deepclone(formData)
    let params = {
      startDate: moment(values.time[0]).format('YYYY-MM-DD'),
      endDate: moment(values.time[1]).format('YYYY-MM-DD'),
      currentPage,
      pageSize,
      ...values,
    }
    let webSide = 1;
    let token = Storage.get(TOKEN);
    let Authorization = 'Bearer ' + token;
    let excel = `${window.location.origin}/manager/merchantOrder/rechargeExport`;
    fetch(excel, {
      method: 'post',
      params,
      headers: new Headers({
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        Authorization,
        webSide
      }),
    })
    .then(response => response.blob())
    .then(blob => {
      if(blob.type == "application/json") {
        let reader: any = new FileReader(); // 创建读取文件对象
        reader.readAsText(blob, 'utf-8');
        reader.addEventListener("loadend", () => {
          let res = JSON.parse(reader.result);
          message.error(res.msg);
        });
        return;
      }
      let url = window.URL.createObjectURL(blob);
      let a = document.createElement('a');
      a.style.display = 'none';
      a.href = url;
      a.download = '充值订单';
      a.click();
      window.URL.revokeObjectURL(url);
    });
  };
  const callbackFn = async (transId) => {
    try {
      setLoading(true)
      let res =  await callback({
        transId
      })
      if(res.code === 0) {
        message.success('回调成功')
        searchData()
      }
      setLoading(false)
    } catch (error) {
      console.log(error)
    }
  };
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    onFinish()
    getTotal()
  })
  //改变搜索条件更新
  useEffect(() => {
    if(first) {
      searchData()
    }
    return () => {};
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [currentPage, pageSize])
  // 首次更新
  useEffect(() => {
    searchData()
    first = true
    return () => { 
      first = false
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  
  // 初始化
  return (
  <div>
    <div>
      <BreadcrumbBox list={breadcrumbList}></BreadcrumbBox>
      <div className='agent-main'>
      <Form
        initialValues={values} 
        form={searchForm} 
        onFinish={(val) => {
          setFormData(val)
          searchData()
        }}>
          <Card className="formCard" style={{ width: '100%' }} bordered={false}>
            <Row>
              <Col {...layout1}>
                <Form.Item
                  name="time"
                  className="formItem"
                  label="创建日期"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <RangePicker allowClear={false} />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <Form.Item
                  name="platformOrderId"
                  className="formItem"
                  label="平台订单"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Input allowClear placeholder="输入平台订单" />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <Form.Item
                  name="orderSource"
                  className="formItem"
                  label="订单来源"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Select
                    options={orderSourceList}
                  />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <Form.Item
                  name="callbackStatus"
                  className="formItem"
                  label="回调状态"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Select
                    options={callbackStatusList}
                  />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <Form.Item
                  name="merchantNo"
                  className="formItem"
                  label="商户订单号"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Input allowClear placeholder="请输入商户订单号" />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <Form.Item
                  name="status"
                  className="formItem"
                  label="订单状态"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Select
                    options={orderStatusList}
                  />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <Form.Item
                  name="merchantCode"
                  className="formItem"
                  label="商户编号"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Input allowClear placeholder="请输入商户编号" />
                </Form.Item>
              </Col>
              <Col {...layout1}>
                <Form.Item
                  name="merchantName"
                  className="formItem"
                  label="商户账号"
                  labelCol={labelCol}
                  wrapperCol={wrapperCol}
                >
                  <Input allowClear placeholder="请输入商户账号" />
                </Form.Item>
              </Col>
              
              <Col {...layoutbtn}>
                <span className="buttonLeft">
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                  <Button
                    className="reset-btn"
                    type="default"
                    onClick={() => {
                      searchForm.resetFields()
                    }}
                  >
                    重置
                  </Button>
                  <Button
                    className="reset-btn"
                    type="primary" 
                    onClick={() => {exportExcel()}}>
                    导出
                  </Button>
                </span>
              </Col>
            </Row>
          </Card>
        </Form>
        <div className='table-box'>
          <Card>
            <div className='table'>
              <Table
                loading={loading}
                size='middle'
                bordered
                scroll={{ x: 1224 }}
                rowKey={'id'}
                className='antd-table'
                dataSource={dataSource}
                pagination={{
                  size: 'default',
                  current: currentPage,
                  total: total,
                  showSizeChanger: true,
                  pageSize: pageSize,
                  onChange: (page, pagesize) => {}
                }}
                columns={columns} />
            </div>
            <div className="bottom">
              <span>总金额：{pageSum}</span>
              <span>当前页汇总金额：{allSum}</span>
            </div>
          </Card>
        </div>
      </div>
    </div>
  </div>
  )
}
export default withRouter(Deposit)